﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using com.IronOne.BoardAppWeb.Models.Entity;
using System.Web.Security;
using System.Web.SessionState;
using com.IronOne.BoardAppWeb.Controllers;

namespace com.IronOne.BoardAppWeb.Models.Auth
{

    public class RoleAuthorizationService
    {
        // TODO : Change this when new role is added
        static aspnet_Roles[] rolesinDB;
        
        static RoleAuthorizationService()
        {
            using (BoardAppProductEntities context = new BoardAppProductEntities())
            {
                rolesinDB = (from p in context.aspnet_Roles select p).ToArray();
            }
        }

        public static Boolean IsAuthorized(string action_fmt)
        {
            string[] userroles = Roles.GetRolesForUser(HttpContext.Current.User.Identity.Name);

             foreach (var userrole in userroles)
                {
                    return rolesinDB.Any(x=> ((x.RoleName == userrole) && (x.Description.Contains(action_fmt))));
                }

            return false;
        }

        public static string[] IsAuthorizedOptimized(string fmt)
        {
            string[] userroles=null;
            BaseController bc = new Controllers.BaseController();

            //checks whether the logged in user's password has expired; if so blocks all menu actions
            if ((Membership.GetUser(HttpContext.Current.User.Identity.Name).LastPasswordChangedDate.AddDays(int.Parse(ConfigurationManager.AppSettings["PasswordExpiryPeriod"])) - DateTime.Now).Days >= 0 || (string.Compare(fmt, "XML", true) == 0))
            {
                userroles = Roles.GetRolesForUser(HttpContext.Current.User.Identity.Name);
            }
            else 
            {
                //userroles = Roles.GetRolesForUser("emptyRole");
                userroles = new string[] { "emptyRole" };
            }
           
            return userroles;
        }


        public static aspnet_Roles[] getRolesinDB()
        {
            return rolesinDB;
        }

    }
}